package com.sinothk.gpserver.modules.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.gpserver.modules.biz.entity.GroupMemberDto;
import com.sinothk.gpserver.modules.biz.entity.GroupMemberEntity;
import com.sinothk.gpserver.modules.biz.entity.GroupUserDto;
import com.sinothk.gpserver.modules.biz.entity.RoomEntity;
import com.sinothk.gpserver.modules.biz.mapper.GroupMemberMapper;
import com.sinothk.gpserver.modules.biz.mapper.RoomMapper;
import com.sinothk.gpserver.modules.biz.service.IGroupMemberService;
import com.sinothk.gpserver.modules.system.entity.LoginEntity;
import com.sinothk.gpserver.modules.system.entity.UserEntity;
import com.sinothk.gpserver.modules.system.mapper.UserMapper;
import com.sinothk.gpserver.util.PageDataUtil;
import com.sinothk.server.support.annotation.callback.BizException;
import com.sinothk.server.support.entity.PageData;
import com.sinothk.server.support.entity.PageVo;
import com.sinothk.server.support.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 俱乐部成员相关 服务实现类
 * </p>
 *
 * @author Liang Y.t.
 * @since 2021-08-29
 */
@Service
public class GroupMemberServiceImpl extends ServiceImpl<GroupMemberMapper, GroupMemberEntity> implements IGroupMemberService {

    @Resource
    private GroupMemberMapper groupMemberMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 查询分页数据
     *
     * @param pageVo 分页参数
     * @return PageData
     */
    @Override
    public PageData<GroupMemberEntity> page(PageVo<GroupMemberEntity> pageVo) {
        Page<GroupMemberEntity> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        Page<GroupMemberEntity> iPage = groupMemberMapper.selectPage(page, null);

        // 组装
        PageData<GroupMemberEntity> rspPageData = new PageData<>();
        rspPageData.setPageNum(iPage.getCurrent());
        rspPageData.setPageSize(iPage.getSize());
        rspPageData.setCurrent(iPage.getCurrent());
        rspPageData.setTotal(iPage.getTotal());
        rspPageData.setData(iPage.getRecords());

        return new PageDataUtil<GroupMemberEntity>().create(iPage);
    }

    /**
     * 分页列表-根据俱乐部查成员
     *
     * @param pageVo 分页列表-根据俱乐部查成员
     * @return PageData
     */
    @Override
    public PageData<GroupMemberDto> pageForGroupId(PageVo<GroupMemberEntity> pageVo) {
        if (pageVo == null || pageVo.getData() == null || StringUtil.isEmpty(pageVo.getData().getGroupId())) {
            throw new BizException("分页参数data没有必传值：groupId");
        }

        Page<GroupMemberEntity> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        IPage<GroupMemberDto> iPage = groupMemberMapper.pageForGroupId(page, pageVo.getData().getGroupId());
        return new PageDataUtil<GroupMemberDto>().create(iPage);
    }

    @Override
    public GroupUserDto getGroupMemberByRoomNumAndAccount(String roomNum, String account) throws Exception {
        if (StringUtils.isEmpty(roomNum)) throw new Exception("房间号[roomNum]不能为空");
        if (StringUtils.isEmpty(account)) throw new Exception("用户账号[account]不能为空");

        LambdaQueryWrapper<RoomEntity> wrapperRoom = new LambdaQueryWrapper<>();
        wrapperRoom.eq(RoomEntity::getRoomNum, roomNum);
        List<RoomEntity> rooms = roomMapper.selectList(wrapperRoom);
        if (rooms == null || rooms.size() == 0) throw new BizException("房间" + roomNum + "不存在");
        RoomEntity room = rooms.get(0);

        LambdaQueryWrapper<GroupMemberEntity> wrapperGroupMember = new LambdaQueryWrapper<>();
        wrapperGroupMember
                .eq(GroupMemberEntity::getGroupId, room.getGroupId())
                .eq(GroupMemberEntity::getMemberAccount, account);

        GroupMemberEntity groupMember = this.getOne(wrapperGroupMember);
        UserEntity userEntity = userMapper.selectByAccount(groupMember.getMemberAccount());

        GroupUserDto groupUserD = new GroupUserDto();
        if (groupMember.getMemberCoins() == null || groupMember.getMemberCoins() == 0)
            throw new Exception("你的成员积分不足，请联系群主");
        groupUserD.setOwnCoins(groupMember.getMemberCoins());

        groupUserD.setAccount(userEntity.getAccount());
        groupUserD.setUserAvatar(userEntity.getUserAvatar());
        groupUserD.setUserName(userEntity.getUserName());
        return groupUserD;
    }

    @Override
    public void updateUserCoins(String roomNum, String account, float userCoins) {
        try {
            if (StringUtils.isEmpty(roomNum)) throw new Exception("房间号[roomNum]不能为空");
            if (StringUtils.isEmpty(account)) throw new Exception("用户账号[account]不能为空");

            LambdaQueryWrapper<RoomEntity> wrapperRoom = new LambdaQueryWrapper<>();
            wrapperRoom.eq(RoomEntity::getRoomNum, roomNum);
            List<RoomEntity> rooms = roomMapper.selectList(wrapperRoom);
            if (rooms == null || rooms.size() == 0) throw new BizException("房间" + roomNum + "不存在");
            RoomEntity room = rooms.get(0);

            LambdaQueryWrapper<GroupMemberEntity> wrapperGroupMember = new LambdaQueryWrapper<>();
            wrapperGroupMember
                    .eq(GroupMemberEntity::getGroupId, room.getGroupId())
                    .eq(GroupMemberEntity::getMemberAccount, account);

            GroupMemberEntity groupMember = this.getOne(wrapperGroupMember);
            groupMember.setMemberCoins(userCoins);
            groupMemberMapper.updateById(groupMember);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addUserCoins(String roomNum, String account, float addCoins) {
        try {
            if (StringUtils.isEmpty(roomNum)) throw new Exception("房间号[roomNum]不能为空");
            if (StringUtils.isEmpty(account)) throw new Exception("用户账号[account]不能为空");

            LambdaQueryWrapper<RoomEntity> wrapperRoom = new LambdaQueryWrapper<>();
            wrapperRoom.eq(RoomEntity::getRoomNum, roomNum);
            List<RoomEntity> rooms = roomMapper.selectList(wrapperRoom);
            if (rooms == null || rooms.size() == 0) throw new BizException("房间" + roomNum + "不存在");
            RoomEntity room = rooms.get(0);

            LambdaQueryWrapper<GroupMemberEntity> wrapperGroupMember = new LambdaQueryWrapper<>();
            wrapperGroupMember
                    .eq(GroupMemberEntity::getGroupId, room.getGroupId())
                    .eq(GroupMemberEntity::getMemberAccount, account);

            GroupMemberEntity groupMember = this.getOne(wrapperGroupMember);
            if (groupMember != null) {
                float coins = groupMember.getMemberCoins() == null ? 0f : groupMember.getMemberCoins();
                groupMember.setMemberCoins(coins + addCoins);
                groupMemberMapper.updateById(groupMember);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setGroupPartner(String groupId, String memberAccount) throws Exception {
        if (StringUtils.isEmpty(groupId)) throw new Exception("房间号[groupId]不能为空");
        if (StringUtils.isEmpty(memberAccount)) throw new Exception("成员账号[memberAccount]不能为空");

        LambdaUpdateWrapper<GroupMemberEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(GroupMemberEntity::getGroupId, groupId)
                .eq(GroupMemberEntity::getMemberAccount, memberAccount);
        wrapper.set(GroupMemberEntity::getGroupRole, 3);
        this.update(wrapper);
    }

    @Override
    public PageData<GroupMemberDto> pageGroupMemberForInviterId(PageVo<GroupMemberEntity> pageVo) {
        if (pageVo == null || pageVo.getData() == null || StringUtil.isEmpty(pageVo.getData().getGroupId())) {
            throw new BizException("分页参数data没有必传值：groupId");
        }

        LoginEntity loginEntity = (LoginEntity) SecurityUtils.getSubject().getPrincipal();
        String inviteBy = loginEntity.getAccount();

        Page<GroupMemberEntity> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        IPage<GroupMemberDto> iPage = groupMemberMapper.pageGroupMemberForInviterId(page, pageVo.getData().getGroupId(), inviteBy);
        return new PageDataUtil<GroupMemberDto>().create(iPage);
    }
}
